var express = require("express");
var proxy = require("http-proxy-middleware");
var history = require("connect-history-api-fallback");
var compression = require("compression");
var app = express();
app.use(compression());

var apiUrl = "";
var fileUrl = "";
var os = require("os");
var IPv4, hostName;
hostName = os.hostname();
// console.log(os.networkInterfaces())
let osArr =
  os.networkInterfaces().ens3 ||
  os.networkInterfaces().eth0 ||
  os.networkInterfaces().WLAN;
for (var i = 0; i < osArr.length; i++) {
  if (osArr[i].family === "IPv4") {
    IPv4 = osArr[i].address;
  }
}
if (IPv4 == "172.19.52.112") {
  apiUrl = "http://172.19.141.180:8049"; // 线上 8049端口
  fileUrl = "http://172.19.52.110:8089"; // 线上 8089端口
} else if (IPv4 == '172.18.213.249') { // 测试ip 172.18.213.249
  apiUrl = "http://182.61.29.51:8089"; // 测试
  fileUrl = "http://182.61.29.51:8089";
} else {
  apiUrl = "http://106.14.154.124:8049"; // 测试
  fileUrl = "http://106.15.201.29:8089";
}
console.log("----------local IP: " + IPv4);

app.use(
  "/api",
  proxy({
    target: apiUrl,
    changeOrigin: true,
    pathRewrite: {
      "^/api": ""
    }
  })
);
app.use(
  "/file",
  proxy({
    target: fileUrl,
    changeOrigin: true,
    pathRewrite: {
      "^/file": ""
    }
  })
);
app.use(
  "/ipApi",
  proxy({
    target: "http://freegeoip.net/json/",
    changeOrigin: true,
    pathRewrite: {
      "^/ipApi": ""
    }
  })
);
app.use(
  history({
    index: "./index.html"
  })
);
app.use(express.static("./dist"));
// var port = process.env.PORT || config.build.port
// 生产环境的端口号
var port = 8004;
module.exports = app.listen(port, function (err) {
  if (err) {
    console.log(err);
    return;
  }
  console.log("Listening at http://localhost:" + port + "\n");
});
